/**
 * Created by yaoxinhui on 2018/5/25.
 */
(function () {
  "use strict";

  angular.module('wtPagination', ['angularUtils.directives.dirPagination'])
    .provider('wtPagination', wtPagination);

  /** @ngInject */
  function wtPagination() {
    var _pageSize = 20;

    /**
     * Set default page size
     *
     * @param {int} pageSize
     */
    this.setPageSize = function (pageSize) {
      _pageSize = (+pageSize);
    };

    this.$get = ['$location', function ($location) {
      var instance = {};

      /**
       * Initial current page number and return it
       *
       * @param {String} key
       * @returns {number}
       */
      instance.initCurrentPage = function (key) {
        return $location.search()[key] ? (+$location.search()[key]) : 1;
      };

      /**
       * Set current page
       *
       * @param {Number} page
       * @param {string=} key
       * @returns {Number}
       */
      instance.setCurrentPage = function (page, key) {
        if (angular.isUndefined(key)) {
          key = 'page';
        }
        return $location.search(key, page);
      };

      /**
       * Get default page size
       *
       * @returns {number}
       */
      instance.getDefaultPageSize = function () {
        return _pageSize;
      };

      /**
       * Calculate offset by current page number and page size
       *
       * @param {int} currentPageNum
       * @param {int=} pageSize
       * @returns {number}
       */
      instance.getOffset = function (currentPageNum, pageSize) {
        var size = pageSize ? pageSize : _pageSize;
        return (currentPageNum - 1) * size;
      };

      instance.setPageSize = function (pageSize) {
        _pageSize = (+pageSize);
      };

      return instance;
    }];
  }
})();
